# -*- coding: UTF-8 -*-
import os
import tkinter as tk
from util.runtimeError import runtimeError
import tkinter.messagebox
from tkinter import filedialog
from business import SRInterface
from business import RepairInterface
from business.logger import Logger

# 初始化日志
log = Logger("appUI.py").logger
# 将要改变的量设成全局变量
window = tk.Tk()
v1 = tk.StringVar()
CheckVar1 = tk.IntVar()
CheckVar2 = tk.IntVar()
theEntry = tk.Entry(window, bd=3, width=5)
theText = tk.Text(window, bd=3, height=19, width=35)
theLabel2 = tk.Label(window, textvariable=v1)
width = 400
height = 400
screenwidth = window.winfo_screenwidth()
screenheight = window.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
sub_alignstr = '%dx%d+%d+%d' % (240, 200, (screenwidth - 200) / 2, (screenheight - 200) / 2)
showpath = ""


def button1Action(showpath=showpath):
    log.info("选择图片：")
    file_path = list(filedialog.askopenfilenames(title="选择图片", filetypes=[('图片文件', '*.png *.jpeg *.jpg *.bmp')],
                                                 initialdir=os.getcwd()))
    if len(file_path) == 0:
        log.info("未选择图片")
        return
    theText.configure(state="normal")
    theText.delete(1.0, "end")
    for index, path in enumerate(file_path):
        if index == len(file_path) - 1:
            showpath = showpath + str(index + 1) + '->' + path
            continue
        showpath = showpath + str(index + 1) + '->' + path + '\n\n'
    theText.insert(1.0, showpath)
    theText.configure(state="disabled")
    log.info(showpath)
    log.info("图片选择完毕")


def button2Action():
    try:
        if theText.get(0.0, 'end') == "\n" or theText.get(0.0, 'end') is None:
            raise runtimeError("尚未选择图片！")
        window.attributes("-disabled", 1)
        log.info("执行超分辨....")
        global SR, theButton4
        SR = tk.Toplevel(window)
        SR.title("超分辨设置")
        SR.geometry(sub_alignstr)
        SR.resizable(width=False, height=False)
        SR.iconbitmap(os.getcwd() + "\IM.ico")
        theCheckButton1 = tk.Checkbutton(SR, text="图像放大(4倍)", variable=CheckVar1, onvalue=1, offvalue=0, height=3, width=15)
        theCheckButton2 = tk.Checkbutton(SR, text="原尺寸，增加细节", variable=CheckVar2, onvalue=1, offvalue=0, height=3, width=15)
        theButton4 = tk.Button(SR, text="确定", bd=3, width=5, command=button4Action)
        theCheckButton1.place(x=50, y=10)
        theCheckButton2.place(x=50, y=60)
        theButton4.place(x=100, y=140)
        SR.protocol("WM_DELETE_WINDOW", close_handler)
        SR.mainloop()
    except runtimeError as e:
        print(e)
        log.error(e)
        tk.messagebox.showerror(title='运行错误', message=e.str_explanation)


def button3Action():
    v1.set("运行中，请稍后..")
    theLabel2.configure(fg='red')
    window.update()
    try:
        if theText.get(0.0, 'end') == "\n" or theText.get(0.0, 'end') is None:
            log.error("未选择图片!")
            raise runtimeError("尚未选择图片！")
        theButton1.configure(state='disabled')
        theButton2.configure(state='disabled')
        theButton3.configure(state='disabled')
        filepaths = theText.get(0.0, 'end')
        # 处理图像修复
        log.info("执行图像修复....")
        RepairInterface.repairImage(filepaths, os.getcwd())
        theButton1.configure(state='normal')
        theButton2.configure(state='normal')
        theButton3.configure(state='normal')
        v1.set("未运行")
        log.info("修复完成")
        theLabel2.configure(fg='black')
    except runtimeError as e:
        print(e)
        log.error(e)
        v1.set("未运行")
        theLabel2.configure(fg='black')
        tk.messagebox.showerror(title='运行错误', message=e)
        theButton1.configure(state='normal')
        theButton2.configure(state='normal')
        theButton3.configure(state='normal')


def button4Action():
    v1.set("运行中，请稍后..")
    theLabel2.configure(fg='red')
    window.update()
    try:
        filepaths = theText.get(0.0, 'end')
        cv1 = CheckVar1.get()
        cv2 = CheckVar2.get()
        if cv1 == 0 and cv2 == 0:
            log.error("未勾选超分辨项目")
            return
        if cv1 == 1 and cv2 == 0:
            log.info("运行中，执行：图像放大(4倍)")
            theButton4.configure(state='disabled')
            # 开始处理超分辨放大
            SRInterface.expandImage(filepaths, os.getcwd())
            theButton4.configure(state='normal')
            v1.set("未运行")
            log.info("运行结束")
            theLabel2.configure(fg='black')
        elif cv2 == 1 and cv1 == 0:
            log.info("运行中，执行：原尺寸，增加细节")
            theButton4.configure(state='disabled')
            # 开始处理保真恢复
            SRInterface.restore_orin_size(filepaths, os.getcwd())
            theButton4.configure(state='normal')
            v1.set("未运行")
            log.info("运行结束")
            theLabel2.configure(fg='black')
        else:
            log.info("运行中，执行：图像放大(4倍) & 原尺寸，增加细节")
            theButton4.configure(state='disabled')
            SRInterface.expandImage(filepaths, os.getcwd())
            SRInterface.restore_orin_size(filepaths, os.getcwd())
            theButton4.configure(state='normal')
            v1.set("未运行")
            log.info("运行结束")
            theLabel2.configure(fg='black')
    except runtimeError as e:
        print(e)
        log.error(e)
        window.attributes("-disabled", 0)
        SR.destroy()
        v1.set("未运行")
        theLabel2.configure(fg='black')
        tk.messagebox.showerror(title='运行错误', message=e)


def close_handler():
    window.attributes("-disabled", 0)
    SR.destroy()


def AppUI():
    window.title("ImageMagicDL")
    # geometry参数含义 :height*width+x+y
    window.geometry(alignstr)
    # window不可改变大小
    window.resizable(width=False, height=False)
    window.iconbitmap(os.getcwd() + "\IM.ico")
    v1.set("未运行")
    theLabel1 = tk.Label(window, text="选中图片路径：")
    global theButton1, theButton2, theButton3
    theButton1 = tk.Button(window, text="选择图片", bd=3, width=8, command=button1Action)
    theButton2 = tk.Button(window, text="超分辨", bd=3, width=8, command=button2Action)
    theButton3 = tk.Button(window, text="修复", bd=3, width=8, command=button3Action)
    theLabel1.place(x=20, y=50)
    theLabel2.place(x=300, y=10)
    theButton1.place(x=300, y=200)
    theButton2.place(x=60, y=350)
    theButton3.place(x=250, y=350)
    theText.place(x=30, y=80)
    theText.configure(state="disabled")
    window.mainloop()
